from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker,scoped_session
import sqlalchemy.types

SqlLiteFile = r"E:\learn\project\blogset\database\blogset.db"

class DbCon:
    
    def __init__(self,db_name):
        self.src = getKDBsqlalchemy(db_name)
        self.engine = create_engine(
                self.src,
                max_overflow=1,  # 超过连接池大小外最多创建的连接
                pool_size=10,  # 连接池大小
                pool_timeout=30,  # 池中没有线程最多等待的时间，否则报错
                pool_recycle=-1,  # 多久之后对线程池中的线程进行一次连接的回收（重置）
                pool_pre_ping=True
            )
        self.SessionFactory = sessionmaker(bind=self.engine)
        self.session = scoped_session(self.SessionFactory)
    def exe_sql(self,sql,*values):
        '''

        :param sql: insert语句 包含 占位符
        :param values: 通用语义中的 values 字段 用 列表传入 可多条
        :return: none
        '''
        try:
                # execute会自动完成连接动作
                self.engine.execute(sql,*values)
                
        except Exception as ex:
                print("writedata error:" + str(ex))
                raise ex


class DbConSqlite:

    def __init__(self, db_name):
        self.src = 'sqlite:///{}'.format(db_name)
        self.engine = create_engine(
            self.src
        )
        self.SessionFactory = sessionmaker(bind=self.engine)
        self.session = scoped_session(self.SessionFactory)

    def exe_sql(self, sql, *values):
        '''

        :param sql: insert语句 包含 占位符
        :param values: 通用语义中的 values 字段 用 列表传入 可多条
        :return: none
        '''
        try:
            # execute会自动完成连接动作
            self.engine.execute(sql, *values)
        except Exception as ex:
            print("writedata error:" + str(ex))
            raise ex

    def query_sql(self,sql):
        try:
            # execute会自动完成连接动作
            result = self.engine.execute(sql).fetchall()
            return result
        except Exception as ex:
            print("writedata error:" + str(ex))
            raise ex

SqlLite = DbConSqlite(SqlLiteFile)

if __name__ == '__main__':
    sqllite_a = DbConSqlite(SqlLiteFile)
    sql = '''
    insert into blog_url
    (name,url,creater)
    values
    (?,?,?)
    '''
    data = [("小明","www.xiaoming.com","xiaoming")]
    sqllite_a.exe_sql(sql,data)

